<template>
  <div class="white-list">
    <div class="filter-container">
      <el-input
        v-model="tableQuery.name"
        style="width: 200px;"
        placeholder="请输入报表名称"
        size="small"
        class="filter-item"
      ></el-input>
      <el-button
        size="small"
        @click="handleFilter"
        type="primary"
        class="filter-item"
        ref="btnQuery"
      >
        查询
      </el-button>
      <el-button
        @click="handleReset"
        size="small"
        type="primary"
        class="filter-item"
        ref="btnRefresh"
      >
        重置
      </el-button>
    </div>
    <div style="display: flex;justify-content: flex-end;margin-bottom: 12px;">
      <el-button
        @click="handleEstablish('add')"
        size="small"
        type="primary"
        class="filter-item"
        ref="btnRefresh"
        icon="el-icon-circle-plus-outline"
      >
        新建报表
      </el-button>
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        label="报表名称"
        prop="name"
        align="center"
        width="160px"
      ></el-table-column>
      <el-table-column prop="path" label="报表路径" align="center">
      </el-table-column>
      <el-table-column
        label="创建者"
        prop="create_by"
        align="center"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="create_at"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="100px">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="handleEstablish('update', scope.row)"
          >
            编辑
          </el-button>
          <el-button type="text" size="mini" @click="deleteType(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="update === false ? '新建报表' : '编辑报表'"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      width="500px"
    >
      <el-form
        class="small-space"
        label-position="right"
        label-width="100px"
        style="width: 100%; margin-left:0px;"
      >
        <el-form-item v-if="second === false" label="报表名称">
          <el-input
            size="small"
            type="text"
            v-model="reportData.name"
            placeholder="请输入名单名称（仅支持汉字、英文和数字）"
            style="width: 100%;"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="second === false" label="父级菜单">
          <div style="max-height: 300px;overflow-y: auto;padding-top: 5px;">
            <el-tree
              ref="tree"
              v-model="reportData.parent_id"
              :data="menuOptions"
              :props="defaultProps"
              node-key="id"
              show-checkbox
              :check-strictly="true"
              default-expand-all
              :default-checked-keys="checkedTree"
              @check-change="orgCheckChange"
            >
            </el-tree>
          </div>
        </el-form-item>
        <el-form-item v-if="second === true" label="报表查看权限">
          <el-table
            ref="multipleTable"
            :data="peopleData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              align="center"
              label="角色名称"
              prop="name"
            ></el-table-column>
            <el-table-column type="selection" width="55"> </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel()">
          取 消
        </el-button>
        <el-button
          v-if="second === false"
          size="small"
          type="primary"
          :loading="formSubmiting"
          @click="nextStep()"
        >
          确认
        </el-button>
        <el-button
          v-if="second === true"
          size="small"
          type="primary"
          :loading="formSubmiting"
          @click="save()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { formatTime, shortcutsOptions } from 'utils'
// import TitleContainer from '@/components/title/TitleContainer'
import {
  getMenu,
  getRoleList,
  createRoute,
  createMenu,
  roleAssign,
  reportList,
  updateMenu,
  revokeFrom,
  deleteMenu
} from '@/api/risksystem/establish/index'

const defaultPage = {
  limit: 10,
  page: 1
}
const defaultQuery = {
  name: null
}

export default {
  components: {
    // TitleContainer
  },
  data() {
    return {
      title: '风控管理-个人黑名单',
      statusArr: {
        '1': '有效',
        '2': '无效'
      },
      tableQuery: Object.assign({}, defaultQuery, defaultPage),
      total: 0,
      tableData: [],
      tableArr: [],
      tableLoading: true,
      createdItem: Object.assign({}, defaultQuery),
      formVisible: false,
      formSubmiting: false,
      peopleData: [],
      second: false,
      menuOptions: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      orgsid: [],
      reportData: {
        name: '',
        parent_id: ''
      },
      createRouteRes: {},
      createMenuRes: {},
      checkedTree: [],
      update: false,
      updateData: {},
      peopleOld: [],
      middleOld: [],
      del_item_ids: [],
      multipleSelection: [],
      middleMultipleSelection: [],
      item_ids: []
    }
  },
  computed: {},
  watch: {
    datePicker() {
      this.createdItem.effect_time_start = this.datePicker
        ? this.datePicker[0]
        : ''
      this.createdItem.effect_time_end = this.datePicker
        ? this.datePicker[1]
        : ''
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 报表列表
    getList() {
      this.tableLoading = true
      reportList({
        code: this.tableQuery.code
      }).then(response => {
        if (response.code === 0) {
          this.tableData = response.data.list
        }
      })
    },
    handleFilter() {
      this.tableArr = []
      if (this.tableQuery.name === '' || this.tableQuery.name === null) {
        this.getList()
      } else {
        this.tableData.forEach(item => {
          if (this.tableQuery.name === item.name) {
            this.tableArr.push(item)
          }
        })
        this.tableData = this.tableArr
      }
    },
    handleReset() {
      this.tableQuery = Object.assign({}, defaultQuery)
    },

    // 获取菜单
    getMenu() {
      getMenu().then(response => {
        // console.log(response)
        if (response.code === 0) {
          this.setName([response.data.root])
          this.menuOptions = [response.data.root]
          this.total = Number(response.data.count)
        }
      })
    },
    setName(obj) {
      for (var i in obj) {
        if (obj[i].extra.support_report === false) {
          obj[i].disabled = true
        }
        if (obj[i].children) {
          this.setName(obj[i].children)
        }
      }
      // console.log(obj)
    },
    // 权限配置
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 下一步 创建路径-创建菜单
    nextStep() {
      if (this.reportData.name === '') {
        this.$message.error('报表名称必填！')
        return false
      }
      if (this.reportData.parent_id === '') {
        this.$message.error('父级菜单必选必填！')
        return false
      }
      if (this.update === false) {
        createRoute({
          system_id: 0,
          name: '/report/list/index/' + Date.now(),
          remark: this.reportData.name
        }).then(response => {
          this.createRouteRes = response.data
          if (response.code === 0) {
            createMenu({
              name: this.reportData.name,
              code: '',
              icon: 'component',
              route: this.createRouteRes.name,
              parent_id: this.reportData.parent_id,
              data: '',
              remark: '',
              extra: {
                support_report: false,
                is_report: true
              }
            }).then(response => {
              if (response.code === 0) {
                this.createMenuRes = response.data
                this.$message.success('报表创建成功！')
                this.second = true
              }
            })
          }
        })
        getRoleList({
          with_children: false
        }).then(response => {
          this.peopleData = response.data.list
        })
      } else {
        updateMenu({
          id: this.updateData.id,
          name: this.reportData.name,
          code: '',
          icon: 'component',
          type: '',
          route: this.updateData.route,
          parent_id: this.orgsid[0],
          data: '',
          remark: '',
          extra: {
            support_report: false,
            is_report: true
          }
        }).then(response => {
          if (response.code === 0) {
            this.createMenuRes = response.data
            this.second = true
            this.$message.success('报表修改成功！')
          }
        })
        getRoleList({
          with_children: true
        }).then(response => {
          this.peopleOld = []
          this.peopleData = []
          this.peopleData = response.data.list
          var _this = this
          for (let i = 0; i < this.peopleData.length; i++) {
            // console.log(this.peopleData)
            var index = this.peopleData[i].children.forEach(item => {
              if (item.name === this.updateData.route) {
                this.peopleOld.push(this.peopleData[i])
              }
            })
          }

          this.$nextTick(() => {
            this.peopleOld.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row)
            })
          })
        })
      }
    },
    save() {
      this.middleOld = []
      this.middleMultipleSelection = []
      this.middleOld = this.peopleOld
      this.middleMultipleSelection = this.multipleSelection
      var identical = new Array()
      for (let i = 0; i < this.multipleSelection.length; i++) {
        for (let j = 0; j < this.peopleOld.length; j++) {
          if (this.peopleOld[j] === this.multipleSelection[i]) {
            identical.push(this.peopleOld[j])
          }
        }
      }
      this.middleOld = this.getArrDifference(this.middleOld, identical)
      this.middleMultipleSelection = this.getArrDifference(
        this.middleMultipleSelection,
        identical
      )
      // 编辑权限移除
      this.del_item_ids = []
      this.middleOld.forEach(item => {
        this.del_item_ids.push(item.id)
      })
      if (this.del_item_ids.length > 0) {
        revokeFrom({
          name: this.updateData.route,
          item_ids: this.del_item_ids
        }).then(response => {
          if (response.code === 0) {
            this.formVisible = false
            this.getList()
            this.second = false
            this.$message.success('权限设置成功！')
          }
        })
      }
      // 编辑权限添加
      this.item_ids = []
      this.middleMultipleSelection.forEach(item => {
        this.item_ids.push(item.id)
      })
      if (this.item_ids.length > 0) {
        roleAssign({
          name:
            this.update === false
              ? this.createRouteRes.name
              : this.updateData.route,
          item_ids: this.item_ids
        }).then(response => {
          if (response.code === 0) {
            this.formVisible = false
            this.getList()
            this.second = false
            this.$message.success('权限设置成功！')
          }
        })
      }
    },
    getArrDifference(arr1, arr2) {
      return arr1.concat(arr2).filter(function(v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v)
      })
    },
    cancel() {
      this.second = false
      this.formVisible = false
      this.peopleOld = []
      this.peopleData = []
      this.multipleSelection = []
    },
    handleEstablish(action, data = {}) {
      this.getMenu()
      this.orgsid = []
      this.formVisible = true
      if (action === 'add') {
        this.checkedTree = []
        this.reportData = {
          name: '',
          parent_id: ''
        }
        this.update = false
      } else {
        this.reportData = {
          name: data.name,
          parent_id: data.parent_id
        }
        var arr = [data.parent_id]
        this.orgsid.push(data.parent_id)
        this.updateData = data
        this.update = true
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(arr)
          this.checkedTree = arr
        })
      }
    },
    // 单选功能
    orgCheckChange(data, checked, indeterminate) {
      this.reportData.parent_id = data.id
      // 获取当前选择的id在数组中的索引
      const indexs = this.orgsid.indexOf(data.id)
      // 如果不存在数组中，并且数组中已经有一个id并且checked为true的时候，代表不能再次选择。
      if (indexs < 0 && this.orgsid.length === 1 && checked) {
        // 设置已选择的节点为false 很重要
        this.$refs.tree.setChecked(data, false)
        this.$message({
          message: '只能选择一个父级菜单！',
          type: 'error',
          showClose: true
        })
      } else if (this.orgsid.length === 0 && checked) {
        // 发现数组为空 并且是已选择
        // 防止数组有值，首先清空，再push
        this.orgsid = []
        this.orgsid.push(data.id)
      } else if (indexs >= 0 && this.orgsid.length === 1 && !checked) {
        // 再次直接进行赋值为空操作
        this.orgsid = []
      }
    },
    // 删除
    deleteType(id) {
      console.log(id)
      deleteMenu({
        id: id,
        delete_route: true
      }).then(response => {
        if (response.code === 0) {
          this.$message.success('删除成功！')
          this.getList()
          this.$router.go(0)
        }
      })
    }
  }
}
</script>
<style scoped>
.white-list {
  padding: 20px;
}
</style>
